<template>
    <div class="roleList">
      <div class="roleList_buttons">
          <Button type="primary" style="marginRight:8px" @click="(addEmployeeMess={}) && (addEmployee = true)">新建角色</Button>
      </div>
      <Table ref="TableHeight" class="table" :max-height="onresizeHeight" :columns="columns1" :data="data1" ></Table>
      <!-- 分页 -->
      <div class="pagePublicStyle" v-show="pageData.total > 0">
         <div class="totalCount">
             当前第 {{pageData.page}} 页， 
             当前第 {{(pageData.page-1)*pageData.rows+1}} 条到第 {{pageData.page*pageData.rows>pageData.total?pageData.total:pageData.page*pageData.rows}} 条，
             共 {{pageData.total}} 条
         </div>
        <Page :current="pageData.page" :total="pageData.total" :page-size-opts="pageData.pageSizeOpts" @on-change="pageOnChangeFun" @on-page-size-change="pageOnPageSizeChangeFun" show-elevator show-sizer />
      </div>
      <!-- table 头部筛选 -->
      <table_filter :options="options" @cancelFilterFun="cancelFilterFun" @okFilterFun="okFilterFun"></table_filter>
      <!-- 新建部门 -->
     <Modal v-model="addEmployee" width="500" title="新建角色">
        <Form ref="addEmployee" :model="addEmployeeMess" :rules="addEmployeeMessRule" :label-width="100">
            <FormItem label="角色名称：" prop="roleName">
              <Input v-model="addEmployeeMess.roleName" placeholder="请填写角色名称"></Input>
           </FormItem>
           <FormItem label="备注：" prop="roleDesc">
              <Input v-model="addEmployeeMess.roleDesc" type="textarea" :autosize="{minRows: 3,maxRows: 8}" placeholder="请填写角色备注"></Input>
           </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="addEmployee = false">取消</Button>
          <Button type="primary" @click="newEmployee('addEmployee')">确定</Button>
        </div>
     </Modal>
    </div>
    
</template>
<script>
  import table_filter from '@/components/table_filter';
  import { getRoleList, getRoleAdd, getRoleUpdate, getRoleDelete} from '@/api/system_center'
  export default {
    components: {
      table_filter
    },
    data() {
     const ruleValidateName = (rule, data, callback) =>{
        if(!data || data.length>15)return callback("请输入不超过15个字符长度的部门名称")
      callback()
    }
     return {
          onresizeHeight: 0,
          pageData: {
            total: 0,
            page: 1,
            rows: 10,
            pageSizeOpts: [10,20, 30, 40, 50]
          },
          options: {
            type: '',   // form类型  Input / DatePicker / Checkbox / Select / 操作配置头部
            placeholder: '',  // 提示语
            left: -1000,    // 弹框fixed => left
            iconLeft: 0,  // 弹框icon => left
            top: -1000,    // 弹框fixed => top
            width: 218,   // 弹框fixed => top
            setTimeout: null,    // 鼠标离开三角形 200毫秒 关闭弹框
            customerName: '',  // 客户姓名 字段
            phoneNumber: '', // 电话 字段
            areaVal: [],  // 地区 字段
            //areaList: [{name: '香蕉', val: '11'}, {name: '苹果', val: '22'}],  // 地区 字段
            //sourceVal: [],  // 来源 字段
            //sourceList: [{name: '香蕉', val: '11'}, {name: '苹果', val: '22'}],  // 来源 数据
           // customerLevelVal: [], // 客户等级 字段
           // customerLevelList: [{name: '香蕉', val: '11'}, {name: '苹果', val: '22'}],  // 客户等级 数据
           // creationTimeVal: '',  // 创建时间 字段
           // autoCompleteVal: '', // 服务人员 字段
           daterange: '',   // 年月日
           // datetimerange: '',  // 年月日时分秒
           // multipleCheckbox: [],  // Checkbox 字段
           // checkboxList: [{name: '香蕉', val: '11'}, {name: '苹果', val: '22'}], // Checkbox数据
           // selectVal: [],  // Select 多项 字段
           // selectList: [{name: '香蕉', val: '11'}, {name: '苹果', val: '22'}], // select数据
           // operatingVal: [],   // 操作 字段
            // tableTitleList: [{name: '订单编号', val: '11', selected: false}, {name: '输入范围', val: '22', selected: false}, {name: '订单编号', val: '11', selected: false}, {name: '输入范围', val: '22', selected: false}, {name: '订单编号', val: '11', selected: false}, {name: '输入范围', val: '22', selected: false}]     // 操作 数据
            tableTitleList:[],
          },
          columns1: [
            {
              title: '角色名称',
              key: 'roleName',
              minWidth: 120,
              render: (h, params) => {
                return h("div", [
                  h(
                    "span",
                    {
                      style: {
                        display: "inline-block",
                        width: "100%",
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap"
                      },
                      domProps: {
                        title: params.row.roleName
                      }
                    },
                    params.row.roleName
                  )
                ]);
              },
              renderHeader: (h, params) => {
                return h('div',[
                  h('span', {}, '角色名称'),
                  h('Icon', {
                    props: {
                      type: 'ios-arrow-down',
                      size: '16'
                    },
                    style: {
                      marginLeft: '5px'
                    },
                    nativeOn: {
                      'mouseover': (event) => {
                        event.stopPropagation();
                        this.thMouseoverFun(event, 'input-customerName', '请输入角色名称', 218);
                      },
                      'mouseleave': (event) => {
                        event.stopPropagation();
                        this.thMouseoutFun();
                      }
                    }
                  })
                ])
              }
            },
            {
              title: '创建人',
              key: 'creater',
              minWidth: 120,
            //   render: (h, params) => {
            //     return h('div',  this.$options.filters.mobilePhoneNumberFourAsterisk(params.row.phone) || '-');
            //   },
              // renderHeader: (h, params) => {
              //   return h('div',[
              //     h('span', {}, '创建人'),
              //     h('Icon', {
              //       props: {
              //         type: 'ios-arrow-down',
              //         size: '16'
              //       },
              //       style: {
              //         marginLeft: '5px'
              //       },
              //       nativeOn: {
              //         'mouseover': (event) => {
              //           event.stopPropagation();
              //           this.thMouseoverFun(event, 'input-phoneNumber', '请输入创建人', 218);
              //         },
              //         'mouseleave': (event) => {
              //           event.stopPropagation();
              //           this.thMouseoutFun();
              //         }
              //       }
              //     })
              //   ])
              // }
            },
            {
              title: '创建时间',
              key: 'createTime',
              minWidth: 180,
              // renderHeader: (h, params) => {
              //   return h('div',[
              //     h('span', {}, '创建时间'),
              //     h('Icon', {
              //       props: {
              //         type: 'ios-arrow-down',
              //         size: '16'
              //       },
              //       style: {
              //         marginLeft: '5px'
              //       },
              //       nativeOn: {
              //         'mouseover': (event) => {
              //           event.stopPropagation();
              //           this.thMouseoverFun(event, 'datePicker-creationTimeVal-daterange', '请选择时间', 260);
              //         },
              //         'mouseleave': (event) => {
              //           event.stopPropagation();
              //           this.thMouseoutFun();
              //         }
              //       }
              //     })
              //   ])
              // }
            },
              {
              title: '平台权限',
              key:'loginApp',
              minWidth: 240,
              render(h, params){
                 return  h('div',[
                   h('span',`后台权限: ${params.row.loginWeb == 1?'有':'无'}`),
                   h('br'),
                   h('span',`app权限: ${params.row.loginApp == 1?'有':'无'}`)
                 ])
              }
            },
            {
              title: '备注',
              key: 'roleDesc',
              minWidth: 240,
            },
            {
              title: '操作',
              key: 'address',
              fixed: 'right',
              width: 180,
              align: 'center',
              render: (h, params) => {
                let arr = ['店长','运营策划','管理员'],flag = arr.findIndex(item=>item == params.row.roleName);
                return h('div', [
                  h('Button', {
                    props:{
                      type : "text"
                    },
                    on: {
                      click: (e) => {
                        e.stopPropagation();
                         this.viewClick(params.row);
                      }
                    }
                  }, '权限配置'),
                   h('Button', {
                    props:{
                      type : "text",
                      disabled:flag>-1
                    },
                    style:{
                       color:'red',
                       padding:'0 6px'
                    },
                    on: {
                      click: (e) => {
                        e.stopPropagation();
                        this.editMess(params.row)
                      }
                    }
                  }, '编辑'),
                   h('Button', {
                    style:{
                       color:'rgb(25, 190, 107)',
                    }, 
                    props:{
                      type : "text",
                      disabled:flag>-1
                    },
                    on: {
                      click: (e) => {
                        e.stopPropagation();
                        this.openAuthority(params.row)
                        // this.deleEmployee = true;
                      }
                    }
                  }, params.row.validate == 1?'禁用':'开启'),

                ]);
              },
              // renderHeader: (h, params) => {
              //   return h('div',[
              //     h('span', {}, '操作'),
              //     h('Icon', {
              //       props: {
              //         type: 'md-settings',
              //         size: '16'
              //       },
              //       style: {
              //         marginLeft: '5px'
              //       },
              //       nativeOn: {
              //         'mouseover': (event) => {
              //           event.stopPropagation();
              //           this.thMouseoverFun(event, 'tableTitle-operatingVal-tableTitleList', '', 300);
              //         },
              //         'mouseleave': (event) => {
              //           event.stopPropagation();
              //           this.thMouseoutFun();
              //         }
              //       }
              //     })
              //   ])
              // }
            }
          ],
          data1: [],
          addEmployeeMessRule:{
            roleName: [
              { validator:ruleValidateName, trigger: 'blur' }
            ], 
          },
          addEmployee:false,
          addEmployeeMess:{
             roleName:''
          },
   }
  },
    methods: {
      //编辑
      editMess(mess){
        this.addEmployeeMess = Object.assign(this.addEmployeeMess,mess);
        this.addEmployee = true;
      },
     //点击新建员工按钮
     newEmployee(name){
       this.$refs[name].validate((valid) => {
           if (valid) {
               let params = this.addEmployeeMess.roleId?this.addEmployeeMess:Object.assign(this.addEmployeeMess,{type:1,validate:1});
               params.roleId?getRoleUpdate(params).then(res=>{
                  this.$Message.success("修改成功");
                  this.addEmployee = false;
                  this.$refs[name].resetFields();
                  this.getRoles({page:1})  
               }).catch(err=>this.$Message.error(err))
               :getRoleAdd(params).then(res=>{
                 this.$Message.success("添加成功")
                  this.addEmployee = false;
                  this.$refs[name].resetFields();
                  this.getRoles({page:1})
               }).catch(err=>this.$Message.error(err))
              
           } 
        })
     }, 
      // table 鼠标移到三角形事件
      thMouseoverFun(event, type, placeholder, width) {
        this.options.type = type
        this.options.placeholder = placeholder
        this.options.left = event.currentTarget.getBoundingClientRect().left - (width/2 - 5) <= 200 ? 200 : (event.currentTarget.getBoundingClientRect().left - (width/2 - 5) + width) > document.documentElement.clientWidth ? (document.documentElement.clientWidth - width) : event.currentTarget.getBoundingClientRect().left - (width/2 - 5)
        this.options.iconLeft = event.currentTarget.getBoundingClientRect().left
        this.options.top = event.currentTarget.getBoundingClientRect().top + 24
        this.options.width = width
      },
      // table 鼠标离开三角形事件
      thMouseoutFun() {
        this.options.setTimeout = setTimeout(() => {
          this.options.left = -1000 
          this.options.top = -1000
        },100)
      },
      // table from 取消事件
      cancelFilterFun(options) {
        console.log('cancelFilterFun', options)
      },
      // table from 确定事件
      okFilterFun(options) {
        let { customerName } = options;
        this.getRoles({roleName:customerName, page:1})
      },
      // 分页 页码改变事件
      pageOnChangeFun(page) {
          this.pageData.page = page;
          this.getRoles()
      },
      // 分页 每页条数改变事件
      pageOnPageSizeChangeFun(rows) {
        this.pageData.rows = rows;
         this.pageData.page = 1;
        this.getRoles()
      },
      // 初始化获取数据
      initData() {
        this.getRoles()
        this.$nextTick(() => {
          this.onresizeHeight = window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 100
        });
      },
      //获取员工列表
      getRoles(params={}){
        let {page, rows} = this.pageData
        params = Object.assign({page,rows},params)
       getRoleList(params).then(res=>{
         console.log("获取角色列表",res)
         this.data1 = res.list;
         this.pageData.total = res.total-0;
       })
        
      },
      // 权限配置
      viewClick(val) {
         //this.editEmployee = true;
         //this.editEmployeeMess = val;
         this.$router.push({
             path:"/system_center/roleControl/roleControling",
             name: 'roleControling',
             query:{
               id:val.roleId,
               web:val.loginWeb,
               app:val.loginApp
             }
         })
      },
      //编辑点击确定
      editEmployeeSure(name){
        this.$refs[name].validate((valid) => {
           if (valid) {
               console.log("成功")
               //调取变更部门接口
               //this.$refs[name].resetFields();
           } 
        })
      },
      //开启禁用人员确定按钮
      deleEmployeeSure(name){
         this.$refs[name].validate((valid) => {
           if (valid) {
               console.log("成功")
               this.deleEmployee = false;
               //调取变更部门接口
               //this.$refs[name].resetFields();
           } 
        }) 
      },
      //开启禁用人员
      openAuthority(mess){
          //调取权限接口
          let {roleId,  roleName, roleDesc,validate} = mess;
        validate = validate == 1?'2':"1"
        let params ={validate,roleId};
        getRoleUpdate(params).then(res=>{
          this.$Message.success("修改成功")
          console.log("修改结果",res);
          this.getRoles()  
        }).catch(err=>this.$Message.error(err))
      }
    },
    computed: {

    },
    created() {
      // 初始化获取数据
      // console.log('测试111111')
      this.initData()
    },
    activated() {

    },
    deactivated() {

    },
    mounted() {
      window.onresize = () => {
        return (() => {
          setTimeout(() => {
            this.onresizeHeight = window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 150
          }, 10);
        })();
      };
    },
    watch: {
      // "$route"(to, from) {
      //   if(to.path == "######") {
      //     this.initData();
      //   }
      // }
    },
  }
</script>
<style lang="scss" scoped>
  .roleList{
      padding: 20px;
      height: calc(100% - 20px);
    .allCustomersP{
      padding: 8px 14px;
    }
    &_buttons{
      margin: 20px;
      text-align: left; 
    }
   /deep/.ivu-table-wrapper{
       height: 100%;
   }
   /deep/.ivu-table th{
       background-color: #f6f8fa;
   }
   /deep/.ivu-btn-text{
     padding: 0 2px;
   }
  }
  /* page */
  .pagePublicStyle{
    text-align: right;
    padding: 14px 0;
    margin-right: 30px;
  }
  .totalCount{
    float: left;
    line-height: 34px;
    padding-left: 20px;  
  }
 .table {
  .ivu-modal-header {
    border-bottom: 1px solid #e8eaec;
    padding: 14px 16px;
    line-height: 1;
  }
  th .ivu-table-cell-with-selection{
    position: relative;
  }
  th .ivu-table-cell-with-selection::after{
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: #f8f8f9;
    z-index: 99;
  }
}

</style>
